/**
 * 身份证验证
 * @Author: YangYun
 * @Date: 2020/4/13 11:45
 */
package validata

import (
    "regexp"
)

func IdCard(idCard string) bool {
    switch len(idCard) {
        case 15:
            return check15card(idCard)
        case 18:
            return verifyIdCard(idCard)
    }
    return false
}

// 15位身份证
func check15card(idCard string) bool {
    return regexp.MustCompile(`^\d{15}$`).MatchString(idCard)
}

// 18位身份证
func check18card(idCard string) bool {
    return regexp.MustCompile(`^\d{15}$`).MatchString(idCard)
}

func verifyIdCard(idCard string) bool {
    if len(idCard) != 18 {
        return false
    }
    factor := []int{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}
    verifyList := "10X98765432"

    checkSum := 0
    for i,v := range idCard[0:17] {
        checkSum += (int(v) - 48) * factor[i]
    }
    index := checkSum % 11
    return verifyList[index:index + 1] == idCard[17:18]
}